package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.master.EntityFileDownloadInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.food.OrderRefundRequest;
import com.ocom.common.request.payconfig.food.OrderSummaryRequest;
import com.ocom.common.request.payconfig.mealorder.GetOrderDishesRequest;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.payhandle.FeeRefundRequest;
import com.ocom.common.request.payhandle.GetRecordProcessRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
//@PreAuthorize("@pms.hasRole('ROLE_WEB')")
public class DishesController {

    @Autowired
    private PayConfigClientService payConfigClientService;
    @Autowired
    private PayHandleFeignService payHandleFeignService;
    @Autowired
    private XfRecordFeign xfRecordFeign;
    @Autowired
    private AccessClientService accessClientService;
    @Autowired
    MqSimpleService mqSimpleService;
    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:菜品分类列表
     * @author lu
     * @date 2022/12/27 10:44
     */
    @PostMapping(WebApiServiceUrl.URL_DishesClassOnShow)
    public Result dishesClassOnShow(@RequestBody JSONObject jsonObject) {
        Integer merchId = jsonObject.getInteger("merchId");
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        if ((yoCiUser.getRole() == 41l || yoCiUser.getRole() == 42l || yoCiUser.getMerchId()>0l) && merchId == 0) {
            merchId = yoCiUser.getMerchId().intValue();
        }
        return payConfigClientService.dishesClassList(jsonObject.getLong("comId"), merchId);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:添加菜品分类
     * @author lu
     * @date 2022/12/27 10:48
     */
    @PostMapping(WebApiServiceUrl.URL_DishesClassAdd)
    public Result dishesClassAdd(@RequestBody JSONObject jsonObject) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        jsonObject.put("userId", yoCiUser.getId());
        return payConfigClientService.newDishesClass(jsonObject);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:修改菜品分类
     * @author lu
     * @date 2022/12/27 10:51
     */
    @PostMapping(WebApiServiceUrl.URL_DishesClassModify)
    public Result dishesClassModify(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.updateDishesClass(jsonObject);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:删除菜品分类（DishesClass/delete）
     * @author lu
     * @date 2022/12/27 10:55
     */
    @PostMapping(WebApiServiceUrl.URL_DishesClassDelete)
    public Result dishesClassDelete(@RequestBody JSONObject jsonObject) {
        Integer merchId = jsonObject.getInteger("merchId");
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
//        if (yoCiUser.getRole() == 41l || yoCiUser.getRole() == 42l || merchId == 0 || yoCiUser.getMerchId()>0l) {
//            merchId = yoCiUser.getMerchId().intValue();
//        }
        return payConfigClientService.removeDishesClass(yoCiUser.getComId(), merchId, jsonObject.getInteger("dishesClassId"));
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:菜品列表
     * @author lu
     * @date 2022/12/27 10:57
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPageOnShow)
    public Result dishesPageOnShow(@RequestBody JSONObject jsonObject) {
        setMerchIdByDepyId(jsonObject);

        String classIds = "";
        if (jsonObject.getInteger("dishesClassId") == 0) {
            if (jsonObject.getInteger("subClass") != 0) {
                classIds = "0";
            }
        }

        if (jsonObject.getInteger("dishesClassId") > 0) {
            Result result = payConfigClientService.getSubDishesClassList(jsonObject);
            if (result.getCode() == 200) {
                JSONObject parseObject = JSON.parseObject(JSON.toJSONString(result.getData()), JSONObject.class);
                classIds = parseObject.getString("classIds");
            }
        }
        jsonObject.put("classIds", classIds);
        Result result = payConfigClientService.getDishesList(jsonObject);
        if(!result.getCode().equals(200)){
            return result;
        }
        HashMap data = (HashMap) result.getData();
        List<JSONObject>  jsonArray= JSON.parseArray(JSON.toJSONString(data.get("list")),JSONObject.class);
        for (JSONObject obj:jsonArray) {
            Result resultA=payConfigClientService.MerchPageInfo(jsonObject.getLong("comId"),obj.getInteger("merchId"));
            if(resultA.getCode().equals(200)){
                EntityXfMerchantInfo entityXfMerchantInfo = JSON.parseObject(JSON.toJSONString(resultA.getData()),EntityXfMerchantInfo.class);
                obj.put("merchName",entityXfMerchantInfo.getMerchName());
//                return ResultUtil.error(result.getCode());
            }

        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",data.get("total"));
        map.put("list",jsonArray);
        return ResultUtil.success(map);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:添加菜品（DishesPage/add）
     * @author lu
     * @date 2022/12/28 16:57
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPageAdd)
    public Result dishesPageAdd(@RequestBody JSONObject jsonObject) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        jsonObject.put("UserId", yoCiUser.getId());
        return payConfigClientService.newDishes(jsonObject);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:修改菜品（DishesPage/modify）
     * @author lu
     * @date 2022/12/28 16:59
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPageModify)
    public Result dishesPageModify(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.updateDishes(jsonObject);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:更换菜品图片（DishesPage/dishesPhoto）
     * @author lu
     * @date 2022/12/28 17:02
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPageDishesPhoto)
    public Result dishesPageDishesPhoto(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.changeDishesPhoto(jsonObject.getLong("comId"), jsonObject.getInteger("dishesId"), jsonObject.getString("photoUrl"));
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:菜品价格表（DishesPage/priceList）
     * @author lu
     * @date 2022/12/30 13:42
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPagepriceList)
    public Result dishesPagepriceList(@RequestBody JSONObject jsonObject) {
        setMerchIdByDepyId(jsonObject);

        return payConfigClientService.getDishesPriceList(jsonObject.getLong("comId"), jsonObject.getInteger("dishesId"), jsonObject.getInteger("merchId"));
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:保存菜品价格（DishesPage/savePrice）
     * @author lu
     * @date 2022/12/30 13:43
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPageSavePrice)
    public Result dishesPageSavePrice(@RequestBody JSONObject jsonObject) {
        setMerchIdByDepyId(jsonObject);

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        jsonObject.put("UserId", yoCiUser.getId());
        return payConfigClientService.setDishesPrice(jsonObject);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:删除菜品价格
     * @author lu
     * @date 2022/12/30 13:53
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPagedeletePrice)
    public Result dishesPagedeletePrice(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.removeDishesPrice(jsonObject);
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:全量下传菜品价格（DishesPage/allDownload）
     * @author lu
     * @date 2022/12/30 14:08
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPageallDownload)
    public Result dishesPageallDownload(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.dishesAllDownload(jsonObject.getLong("comId"), jsonObject.getInteger("merchId"));
    }

    /**
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @Description:获取商户的消费点（DishesPage/getPoints）
     * @author lu
     * @date 2022/12/30 14:13
     */
    @PostMapping(WebApiServiceUrl.URL_DishesPagegetPoints)
    public Result dishesPagegetPoints(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.getPointsByMerch(jsonObject.getLong("comId"), jsonObject.getInteger("merchId"));
    }

    @PostMapping(WebApiServiceUrl.URL_DishesPageAllDishes)
    public Result dishesPageAllDishes(@RequestBody JSONObject jsonObject) {
        return payConfigClientService.getAllDishes(jsonObject.getLong("comId"));
    }

    private void setMerchIdByDepyId(JSONObject jsonObject) {
        if (0 >= jsonObject.getLongValue("merchId")) {
            YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
            jsonObject.put("merchId", yoCiUser.getDeptId());
        }

    }

    //6.6.1已点餐查询（OrderPage/onShow）
    @PostMapping(WebApiServiceUrl.Url_OrderPageOnShow)
    public Result orderPageOnShow(@RequestBody GetOrderDishesRequest request) {

        Date now = new Date();
        if (StringUtils.isBlank(request.getBeginDate())) {
            request.setBeginDate(DateUtil.getStrDate(now, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isBlank(request.getEndDate())) {
            request.setEndDate(DateUtils.getendDate(DateUtils.addMonths(now, 3), DateUtils.YYYY_MM_DD));
        }
        request.setMonthValue(request.getBeginDate().substring(0,7).replace("-",""));

        if(request.isLastMonth()){
            String startMonth = DateUtils.getLastMonth(request.getMonthValue(), 1);
            request.setMonthValue(startMonth);
        }

        return xfRecordFeign.getOrderDishesC(request);


//        Result orderDishes = payConfigClientService.getOrderDishesB(request);
//        if (200 != orderDishes.getCode() || orderDishes.getData()==null) {
//            return orderDishes;
//        }
//        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(orderDishes.getData()));
//        List<EntityXfGoodListDishes> listDishes = JSON.parseArray(jsonObject.getString("records"), EntityXfGoodListDishes.class);
//
//        Result result = payConfigClientService.GetMerchInfo(request.getComId(), null, null, -1, -1, null);
//        Map<Integer, String> merchantInfoMap = new HashMap<>();
//        if (200 == result.getCode() && null != result.getData()) {
//            JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));
//            List<EntityXfMerchantInfo> xfMerchantInfos = JSON.parseArray(JSON.toJSONString(jsonObject1.get("list")), EntityXfMerchantInfo.class);
//            merchantInfoMap = xfMerchantInfos.stream().collect(Collectors.toMap(EntityXfMerchantInfo::getMerchId, EntityXfMerchantInfo::getMerchName));
//        }
//        GetTollPointInfoRequest tollPointInfoRequest = new GetTollPointInfoRequest();
//        tollPointInfoRequest.setCom_id(request.getComId());
//        result = payConfigClientService.getTollPointInfo(tollPointInfoRequest);
//        Map<Integer, String> pointInfoMap = new HashMap<>();
//        if (200 == result.getCode() && null != result.getData()) {
//            JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));
//            List<EntityXfPointInfo> pointInfos = JSON.parseArray(JSON.toJSONString(jsonObject1.get("list")), EntityXfPointInfo.class);
//            pointInfoMap = pointInfos.stream().collect(Collectors.toMap(EntityXfPointInfo::getPointId, EntityXfPointInfo::getPointName));
//        }
//
//        GetConsDeviceInfoRequest getConsDeviceInfoRequest = new GetConsDeviceInfoRequest();
//        getConsDeviceInfoRequest.setCom_id(request.getComId());
//        result = payConfigClientService.getConsDeviceInfo(getConsDeviceInfoRequest);
//        Map<String, String> deviceInfoMap = new HashMap<>();
//        if (200 == result.getCode() && null != result.getData()) {
//            JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));
//            List<EntityXfDeviceInfo> deviceInfos = JSON.parseArray(JSON.toJSONString(jsonObject1.get("list")), EntityXfDeviceInfo.class);
//            deviceInfoMap = deviceInfos.stream().collect(Collectors.toMap(EntityXfDeviceInfo::getDeviceNo, EntityXfDeviceInfo::getDeviceName));
//        }
//
//        List<String> orderNos = listDishes.stream().map(EntityXfGoodListDishes::getOrderNo).collect(Collectors.toList());
//        Map<String, String> xfRecordProcesseMap = new HashMap<>();
//        if (0 < orderNos.size()) {
//            SelectByOrderNosRequest selectByOrderNosRequest = new SelectByOrderNosRequest();
//            selectByOrderNosRequest.setComId(request.getComId());
//            selectByOrderNosRequest.setOrderNos(orderNos);
//
//            result = payHandleFeignService.selectByOrderNos(selectByOrderNosRequest);
//
//
//            if (200 == result.getCode() && null != result.getData()) {
//
//                List<EntityXfRecordProcess> xfRecordProcesses = JSON.parseArray(JSON.toJSONString(result.getData()), EntityXfRecordProcess.class);
//                xfRecordProcesseMap = xfRecordProcesses.stream().collect(Collectors.toMap(EntityXfRecordProcess::getOrderNo, EntityXfRecordProcess::getReserved3));
//            }
//        }
//
//        if (null != listDishes && 0 < listDishes.size()) {
//
//            List<Long> pIds = listDishes.stream().map(EntityXfGoodListDishes::getPId).collect(Collectors.toList());
//
//            GetPersonByPIdsRequest getPersonByPIdsRequest=new GetPersonByPIdsRequest();
//            getPersonByPIdsRequest.setComId(request.getComId());
//            getPersonByPIdsRequest.setPIds(pIds);
//            Result<List<EntityPersonnelInfo>> entityPersonnelInfos = humanClientService.getPersonByIds(getPersonByPIdsRequest);
//
//            for (EntityXfGoodListDishes dishe : listDishes) {
//                dishe.setMerchName(merchantInfoMap.get(dishe.getMerchId()));
//
//                dishe.setPointName(pointInfoMap.get(dishe.getPointId()));
//
//                dishe.setDeviceName(deviceInfoMap.get(dishe.getDeviceNo()));
//
//                dishe.setRemark(xfRecordProcesseMap.get(dishe.getOrderNo()));
//
//                for (EntityPersonnelInfo entityPersonnelInfo:entityPersonnelInfos.getData()){
//                    if(entityPersonnelInfo.getPId().equals(dishe.getPId())){
//                        dishe.setPCode(entityPersonnelInfo.getPCode());
//                        dishe.setPName(entityPersonnelInfo.getPName());
//                        break;
//                    }
//                }
//            }
//        }
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("total", jsonObject.getInteger("total"));
//        map.put("list", listDishes);
//        return ResultUtil.success(map);
    }

    //6.6.2退餐（OrderPage/orderRefund）
    @PostMapping(WebApiServiceUrl.Url_OrderPageOrderRefund)
    public Result orderPageOrderRefund(@RequestBody OrderRefundRequest request) {
        GetRecordProcessRequest processRequest = new GetRecordProcessRequest();
        processRequest.setCompanyId(request.getComId());
        processRequest.setTradeNo(request.getOrderNo());
        Result result = payHandleFeignService.getRecordProcess(processRequest);
        if (200 != result.getCode()) {
            return result;
        }
        EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfRecordProcess.class);

        FeeRefundRequest feeRefund = new FeeRefundRequest();
        feeRefund.setCompanyId(request.getComId());
        feeRefund.setFeeItemId(0);
        feeRefund.setPId(0);
        feeRefund.setRefundAmount(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
        feeRefund.setOrigTradeNo(request.getOrderNo());
        feeRefund.setTradeNo(new Date().getTime() + "C" + request.getComId() + "P" + entityXfRecordProcess.getPId());
        feeRefund.setCheck(false);
        result = payHandleFeignService.paraRefund(feeRefund);

        if (200 != result.getCode()) {
            return result;
        }

        RefundOrderDishesRequest dishesRequest = new RefundOrderDishesRequest();
        dishesRequest.setOrderNo(request.getOrderNo());
        dishesRequest.setComId(request.getComId());
        result = payConfigClientService.refundOrderDishes(dishesRequest);

        return result;
    }

    @PostMapping(WebApiServiceUrl.Url_OrderPageOrderRefundB)
    public Result orderPageOrderRefundB(@RequestBody OrderRefundRequest request) {
        GetRecordProcessRequest processRequest = new GetRecordProcessRequest();
        processRequest.setCompanyId(request.getComId());
        processRequest.setTradeNo(request.getOrderNo());
        Result result = payHandleFeignService.getRecordProcess(processRequest);
        if (200 != result.getCode()) {
            return result;
        }
        EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfRecordProcess.class);

        FeeRefundRequest feeRefund = new FeeRefundRequest();
        feeRefund.setCompanyId(request.getComId());
        feeRefund.setFeeItemId(request.getGoodsId().intValue());
        feeRefund.setPId(0);
        feeRefund.setRefundAmount(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
        feeRefund.setOrigTradeNo(request.getOrderNo());
        feeRefund.setTradeNo(new Date().getTime() + "C" + request.getComId() + "P" + entityXfRecordProcess.getPId());
        feeRefund.setCheck(false);
        result = payHandleFeignService.paraRefundB(feeRefund);

        if (200 != result.getCode()) {
            return result;
        }

        RefundOrderDishesRequest dishesRequest = new RefundOrderDishesRequest();
        dishesRequest.setOrderNo(request.getOrderNo());
        dishesRequest.setComId(request.getComId());
        dishesRequest.setGoodsId(Lists.newArrayList(request.getGoodsId().intValue()));
        result = payConfigClientService.refundOrderDishesB(dishesRequest);

        return result;
    }

    //6.6.3订餐统计（OrderPage/summary）
    @PostMapping(WebApiServiceUrl.Url_OrderPageSummary)
    public Result summary(@RequestBody OrderSummaryRequest request) {
        if (request.getMealNo() != null) {
            request.getMealNos().add(Integer.valueOf(request.getMealNo()));
        }
        return payConfigClientService.orderSummary(request);
    }


    //6.6.3订餐统计（OrderPage/summary）
    @PostMapping(WebApiServiceUrl.Url_OrderPageExport)
    public Result orderPageExport(@RequestBody GetOrderDishesRequest request) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        EntityFileDownloadInfo entityFileDownloadInfo =new EntityFileDownloadInfo();
        entityFileDownloadInfo.setPId(yoCiUser.getId());
        entityFileDownloadInfo.setRemark(JSON.toJSONString(request));
        entityFileDownloadInfo.setStatus(0l);
        entityFileDownloadInfo.setName("点餐明细报表导出");

        Integer id = 1;
        if(request.getType()==1){
            Result result = accessClientService.SendExcelApply(entityFileDownloadInfo);
            if(result.getCode()!=200){
                return ResultUtil.error(ResultEnum.Err_4013);
            }
            id = (Integer)result.getData();
        }

        Date now = new Date();
        if (StringUtils.isBlank(request.getBeginDate())) {
            request.setBeginDate(DateUtil.getStrDate(now, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isBlank(request.getEndDate())) {
            request.setEndDate(DateUtils.getendDate(DateUtils.addMonths(now, 3), DateUtils.YYYY_MM_DD));
        }
        request.setMonthValue(request.getBeginDate().substring(0,7).replace("-",""));


        request.setId(id);
        mqSimpleService.orderMeal(request);

        return ResultUtil.success();
    }
}
